package com.financial.service.heemoney.controller;

import com.financial.service.heemoney.convertor.HeemoneyPayConvert;
import com.financial.service.heemoney.dto.HeemoneyConfigDTO;
import com.financial.service.heemoney.dto.businsess.HeemoneyPayBusinessDTO;
import com.financial.service.heemoney.dto.commmon.HeemoneyPayCommonDTO;
import com.financial.service.heemoney.dto.inparameter.HeemoneyPayInParamDTO;
import com.financial.service.heemoney.dto.param.HeemoneyPayParamDTO;


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2017/7/14.
 */
public class JhzfApplyPay {
    public static void main(String[] args){
        String s = pay();
        System.out.println(s);
    }

    public static String pay (){

        //请求地址
        String requestUrl = "https://pay.heemoney.com/v1/ApplyPay";



        /**
         *所有请求参数
         */
        String method = "heemoney.pay.applypay";//方法
        String version = "1.0";//版本号
        String app_id = "hyp17041449458900000057698DAAB00";//应用ID
        String mch_uid = "4945892094734";//商户号
        //String isv_mch_uid = "22";//服务商商户号
        //String isv_app_id = "222";//服务商应用ID
        String charset = "utf-8";//编码格式
        String sign_type = "MD5";//签名类型
        String sign = "";//签名串
        String timestamp = getDate("yyyyMMddHHmmss");//时间戳
        String key = "5454778B83484969ACFB20BA";//密钥
        String biz_content_ = "";//商务内容

        String out_trade_no = getDate("yyyyMMddHHmmss")+"123";//商户订单号
        String subject = "Nexus Pixel";//订单标题
        String attach = "";//附加数据，在查询API和支付通知中原样返回，可作为自定义参数使用
        String total_fee = "1";//总金额
        String clerk_uid = "";//商户操作员或收银员编号
        String store_uid = "";//商户门店
        String device_code = "";//商户机具终端编号，或盒子编号
        String desk_no = "";//桌号&餐饮等桌号
        String client_ip = "192.168.1.1";//终端IP
        String terminal_info_ = "";//终端信息
        String channel_Type = "WX_JSAPI";//通道类型      demo为扫码
        String pay_option = "";//支付参数信息
        String meta_option = "";//商户定制信息
        String notify_url = "http://www.baidu.com";//异步回调地址
        String return_url = "http://www.baidu.com";//同步返回地址


//        HeemoneyPayCommonDTO heemoneyPayCommonDTO = HeemoneyPayConvert.MAPPER.configDTOConvertCommonDTO(new HeemoneyConfigDTO(),new HeemoneyPayInParamDTO());
        HeemoneyPayCommonDTO  heemoneyPayCommonDTO = null;
        HeemoneyPayBusinessDTO heemoneyPayBusinessDTO = new HeemoneyPayBusinessDTO();
        heemoneyPayBusinessDTO.setAttach(attach);
        heemoneyPayBusinessDTO.setChannel_type(channel_Type);
        heemoneyPayBusinessDTO.setClerk_uid(clerk_uid);
        heemoneyPayBusinessDTO.setClient_ip(client_ip);
        heemoneyPayBusinessDTO.setDesk_no(desk_no);
        heemoneyPayBusinessDTO.setDevice_code(device_code);
        heemoneyPayBusinessDTO.setMeta_option(meta_option);
        heemoneyPayBusinessDTO.setNotify_url(notify_url);
        heemoneyPayBusinessDTO.setOut_trade_no(out_trade_no);
        heemoneyPayBusinessDTO.setPay_option(pay_option);
        heemoneyPayBusinessDTO.setReturn_url(return_url);
        heemoneyPayBusinessDTO.setStore_uid(store_uid);
        heemoneyPayBusinessDTO.setSubject(subject);
        heemoneyPayBusinessDTO.setTerminal_info(terminal_info_);
        heemoneyPayBusinessDTO.setTotal_fee(Integer.parseInt(total_fee));

        HeemoneyPayParamDTO heemoneyPayParamDTO= new HeemoneyPayParamDTO(heemoneyPayCommonDTO,heemoneyPayBusinessDTO);
        System.out.println(heemoneyPayParamDTO.getJsonParam());
        String ret = Post(requestUrl, heemoneyPayParamDTO.getJsonParam());
        //配置请求参数
        /*JSONObject requestParams = new JSONObject();
        requestParams.put("method", method);
        requestParams.put("version", version);
        requestParams.put("app_id", app_id);
        requestParams.put("mch_uid", mch_uid);
        //requestParams.put("isv_mch_uid", isv_mch_uid);
        //requestParams.put("isv_app_id", isv_app_id);
        requestParams.put("charset", charset);
        requestParams.put("sign_type", sign_type);
        requestParams.put("timestamp", timestamp);

        JSONObject biz_content = new JSONObject();
        biz_content.put("out_trade_no",out_trade_no);
        biz_content.put("subject", subject);
        biz_content.put("attach", attach);
        biz_content.put("total_fee", total_fee);
        biz_content.put("clerk_uid", clerk_uid);
        biz_content.put("store_uid", store_uid);
        biz_content.put("device_code", device_code);
        biz_content.put("desk_no", desk_no);
        biz_content.put("client_ip", client_ip);
        biz_content.put("terminal_info", terminal_info_);
        biz_content.put("channel_type", channel_Type);
        biz_content.put("pay_option", pay_option);
        biz_content.put("meta_option", meta_option);
        biz_content.put("notify_url", notify_url);
        biz_content.put("return_url", return_url);

        requestParams.put("biz_content", biz_content.toString());


        //组织签名串
        StringBuilder builder = new StringBuilder();
        builder.append("app_id")       .append("=").append(app_id)                 .append("&")
                .append("biz_content").append("=").append(biz_content.toString()) .append("&")
                .append("charset")     .append("=").append(charset)                .append("&")
                .append("mch_uid")     .append("=").append(mch_uid) 				 .append("&")
                .append("method")      .append("=").append(method)				     .append("&")
                .append("sign_type")   .append("=").append(sign_type)		    	 .append("&")
                .append("timestamp")   .append("=").append(timestamp)		    	 .append("&")
                .append("version")     .append("=").append(version)				 .append("&")
                .append("key")          .append("=").append(key);

        System.out.println("签名参数："+builder.toString());
        sign = MD5en(builder.toString()).toUpperCase();
        requestParams.put("sign",sign);

        System.out.println("签名结果："+sign);
        System.out.println("请求参数："+requestParams);
        String ret = Post(requestUrl,  requestParams.toString());*/
        //返回
        return ret;
    }



    /**
     * MD5加密
     * @param str 需要加密的值
     * @return 加密完成的值(小写)
     */
    public static String MD5en(String str){
        String re_md5 = new String();
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte b[] = md.digest();

            int i;

            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }

            re_md5 = buf.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return re_md5;
    }


    /**
     * 获取当前时间（格式自传）
     * @param dateFormat 要返回的时间格式，例如yyyy/MM/dd HH:mm:ss
     * @return
     */
    public static String getDate(String dateFormat){
        Date date = new Date();
        SimpleDateFormat dateF = new SimpleDateFormat(dateFormat);//可以方便地修改日期格式
        String retu = dateF.format(date);
        return retu;
    }



    /**
     * 发送Http请求类
     * @requestUrl 请求地址
     * @requestData 请求参数
     */
    public static String Post(String requestUrl, String requestData){

        HttpURLConnection connection = null;
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuffer result = new StringBuffer();

        try {
            URL url = new URL(requestUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/json");

            connection.setDoOutput(true);

            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(connection.getOutputStream());
            // 发送请求参数
            out.print(requestData);
            // flush输出流的缓冲
            out.flush();

            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        } catch (Exception e) {
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
        return "Http请求错误";
    }
}


